﻿using System;
using System.Collections.Generic;
using Microsoft.SharePoint;
using System.Linq;
using SPContrib.Extensions;

namespace SPContrib.SharePoint.Extensions
{
    /// <summary>
    /// Extensions for the SPListCollection class
    /// </summary>
    public static class SPListCollectionExtensions
    {
        /// <summary>
        /// Query the collection for SPLists that meets the search criteria
        /// </summary>
        /// <param name="criteria">the search criteria delegate (e.g. list => list.Name() == "SomeList")</param>
        public static IEnumerable<SPList> FindByCriteria(this SPListCollection instance, Predicate<SPList> criteria)
        {
            return from SPList l in instance
                   where criteria(l)
                   select l;
        }

        /// <summary>
        /// Query the collection for SPLists that meets the name criteria
        /// </summary>
        /// <param name="name">the name of the list</param>
        public static IEnumerable<SPList> FindByName(this SPListCollection instance, string name)
        {
            return instance.FindByCriteria(list => list.Name().Equals(name, StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// Query the collection for SPLists that meets the name criteria. 
        /// A boolean indicates if the query was successful or not.
        /// </summary>
        /// <param name="name">the name of the list</param>
        /// <param name="result">the SPList to return if the query is successful</param>
        public static bool TryFindByName(this SPListCollection instance, string name, out SPList result)
        {
            bool match = instance
                            .FindByName(name)
                            .Execute(out result);

            return match;
        }
    }
}
